package com.shunda.pay.utils;

import com.shunda.common.exception.ServiceException;
import com.shunda.pay.config.WxPayConfig;
import com.shunda.pay.dto.WxChatQueryProfitsSharingDto;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.OrdersEntity;
import com.wechat.pay.java.service.profitsharing.model.QueryOrderRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 查询分账结果工具类
 */
public class WxPayQueryProfitsSharingUtil {

    private static final Logger log = LoggerFactory.getLogger(WxPayQueryProfitsSharingUtil.class);

    /**
     * 封装查询分账结果
     */
    private static QueryOrderRequest getQueryProfitsSharingParams(WxChatQueryProfitsSharingDto dto) {
        QueryOrderRequest request = new QueryOrderRequest();
        request.setOutOrderNo(dto.getOutOrderNo());
        request.setTransactionId(dto.getTransactionId());
        return request;
    }

    /**
     * 查询分账
     *
     * @param wxPayConfig 微信配置信息
     * @param param       查询分账结果参数
     * @return
     */
    public static String queryProfitsSharing(WxPayConfig wxPayConfig, WxChatQueryProfitsSharingDto param,
                                             RSAAutoCertificateConfig rsaAutoCertificateConfig) {
        ProfitsharingService service =
                new ProfitsharingService.Builder()
                        .config(rsaAutoCertificateConfig)
                        .build();
        OrdersEntity response = null;
        try {
            QueryOrderRequest request = getQueryProfitsSharingParams(param);
            response = service.queryOrder(request);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信查询分账发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            log.error("微信查询分账服务状态错误，错误信息：{}", e.getMessage());
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
        }
        if (response != null) {
            log.info("微信查询分账成功，返回值：{}", response);
            // 返回分账账单号返回值
            return response.getState().name();
        }
        return "";
    }

}
